<template>
  <el-form
    ref="form"
    class="form-border bold-label"
    label-position="top"
    :model="form"
    :rules="rules"
  >
    <el-form-item label="社区名" prop="title">
      <el-input v-model.trim="form.title" />
    </el-form-item>
    <el-form-item label="社区描述">
      <el-input v-model.trim="form.desc" type="textarea" />
    </el-form-item>
    <el-form-item label="社区封面">
      <div class="flex">
        <el-avatar :size="90" :src="previewAvatar" shape="square" class="m-l-16"/>
        <div class="body-line-height m-l-16">
          <div class="flex">
            <UploadAvatar :preview-url.sync="form.avatar" v-on:avatar="setAvatar" />
            <el-button size="small" class="m-l-10" @click="setAvatar({})">重置</el-button>
          </div>
          <p class="info">仅支持 jpg, jpeg, png 格式的图片类型。<br>图片允许的最大大小为2MB。</p>
        </div>
      </div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit" :loading="loading">确认</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { mapActions } from 'vuex';
import UploadAvatar from '@/components/shared/UploadAvatar';
import { formatCommunity } from '@/components/communities/format';

export default {
  name: 'CommunitySettings', // 社区设置
  components: { UploadAvatar },
  data() {
    return {
      form: JSON.parse(JSON.stringify(this.$store.state.currentCommunity)),
      rules: {
        title: [{ required: true, validator: this.$va.communityTitle, trigger: 'blur' }],
      },
      loading: false,
    };
  },
  computed: {
    previewAvatar() { return this.form.avatar || this.$store.state.currentCommunity.avatar; },
    initUpdateParams() {
      return {
        communityId: this.$route.params.communityId,
        title: this.form.title,
        desc: this.form.desc,
        avatarKey: this.form.avatarKey,
      };
    },
  },
  methods: {
    ...mapActions(['setCurrentCommunity']),
    onSubmit() {
      this.$refs.form.validate((valid, errs) => {
        if (valid) {
          this.loading = true;
          this.$api.communities.update(this.initUpdateParams)
            .then((res) => {
              this.$message.success('修改成功');
              this.setCurrentCommunity(formatCommunity(res.data));
              this.resetForm(); // 重置表单，不然封面上传会出问题
            })
            .catch(() => {})
            .then(() => { this.loading = false; });
        } else this.$refs[Object.keys(errs)[0]].$el.scrollIntoView({ block: 'center' });
      });
    },
    // 重置表单（更新成功时需要更新当前页面的form）
    resetForm() { this.form = JSON.parse(JSON.stringify(this.$store.state.currentCommunity)); },
    // 接受上传组件返回的头像数据
    setAvatar(avatar) {
      this.form.avatar = avatar.url || this.$store.state.currentCOmmunity.avatar;
      this.form.avatarKey = avatar.key;
    },
  },
};
</script>

<style></style>
